package com.jnc.rest.core.des.advice;

import com.alibaba.fastjson.JSONObject;
import com.jnc.rest.util.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Auther: jjn
 * @Date: 2020/2/13
 * @Desc: 自定义请求参数解密
 * 请求加密参数传输格式：  {"obj":"加密串"}
 */
@Slf4j
public class DecryptHttpInputMessage implements HttpInputMessage {

    private HttpHeaders headers;
    private InputStream body;

    public DecryptHttpInputMessage(HttpInputMessage inputMessage, String salt, String charset) throws Exception {
        this.headers = inputMessage.getHeaders();
        String content = IOUtils.toString(inputMessage.getBody(), charset);

        long startTime = System.currentTimeMillis();
        // JSON 数据格式的不进行解密操作
        String decryptBody = "";
        JSONObject obj = JSONObject.parseObject(content);
        String tempContent = obj.getString("obj");
        if (content.startsWith("{") && content.endsWith("}") && StringUtils.isNotBlank(tempContent)) {
            decryptBody = AESUtil.aesDecrypt(tempContent, salt);
        }else{
            throw new IllegalArgumentException("非法请求参数");
        }
        long endTime = System.currentTimeMillis();
        log.debug("Decrypt Time: {}, body: {}, req: {}", (endTime - startTime), decryptBody, content);
        this.body = IOUtils.toInputStream(decryptBody, charset);
    }

    @Override
    public InputStream getBody() throws IOException {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}
